import { useState, useEffect } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { cn } from '@/lib/utils';
import { useCompanyInfo } from '@/hooks/useCompany';

interface NavItem {
  label: string;
  path?: string;
  anchor?: string;
  isExternal?: boolean;
}

const navItems: NavItem[] = [
  { label: '首页', path: '/' },
  { label: '关于我们', anchor: 'about' },
  { label: '新闻动态', path: '/news' },
  { label: '公告公示', path: '/announcements' },
  { label: '业务范围', path: '/services' },
  { label: '联系我们', anchor: 'contact' },
];

export default function Navbar() {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const location = useLocation();
  const navigate = useNavigate();

  // 获取公司信息
  const { data: companyInfo } = useCompanyInfo();

  // Handle scroll event for navbar styling
  useEffect(() => {
    const handleScroll = () => {
      setScrolled(window.scrollY > 10);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  // Handle anchor link clicks
  const handleAnchorClick = (anchor: string) => {
    setIsMenuOpen(false);

    // 如果当前不在首页，先跳转到首页
    if (location.pathname !== '/') {
      navigate('/', { replace: true });
      // 等待页面加载后再滚动到锚点
      setTimeout(() => {
        const element = document.getElementById(anchor);
        if (element) {
          element.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
          });
        }
      }, 100);
    } else {
      // 如果已经在首页，直接滚动到锚点
      const element = document.getElementById(anchor);
      if (element) {
        element.scrollIntoView({
          behavior: 'smooth',
          block: 'start'
        });
      }
    }
  };

  return (
    <header 
      className={cn(
        'sticky top-0 z-50 w-full transition-all duration-300',
        scrolled ? 'bg-white shadow-md py-2' : 'bg-transparent py-4'
      )}
    >
      <div className="container mx-auto px-4">
        <div className="flex items-center justify-between">
          {/* Logo */}
          <div className="flex items-center">
            <Link to="/" className="flex items-center">
              {companyInfo?.company_logo ? (
                <div className="w-10 h-10 rounded-lg overflow-hidden mr-3 border border-gray-200">
                  <img
                    src={companyInfo.company_logo}
                    alt={companyInfo.company_name || '公司Logo'}
                    className="w-full h-full object-contain"
                  />
                </div>
              ) : (
                <div className="w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center mr-3">
                  <span className="text-white font-bold text-xl">EC</span>
                </div>
              )}
              <span className="text-xl font-bold text-blue-800">
                {companyInfo?.company_name || '环境工程咨询'}
              </span>
            </Link>
          </div>

          {/* Desktop Navigation */}
          <nav className="hidden md:flex items-center space-x-8">
            {navItems.map((item) => (
              item.anchor ? (
                <button
                  key={item.anchor}
                  type="button"
                  onClick={() => handleAnchorClick(item.anchor!)}
                  className="text-gray-700 hover:text-blue-600 font-medium transition-colors"
                >
                  {item.label}
                </button>
              ) : (
                <Link
                  key={item.path}
                  to={item.path!}
                  className="text-gray-700 hover:text-blue-600 font-medium transition-colors"
                >
                  {item.label}
                </Link>
              )
            ))}
            {/* <Link
              to="/admin/login"
              className="text-gray-700 hover:text-blue-600 font-medium transition-colors ml-4"
            >
              管理系统
            </Link> */}
          </nav>

          {/* Mobile menu button */}
          <div className="md:hidden">
            <button
              type="button"
              onClick={() => setIsMenuOpen(!isMenuOpen)}
              className="text-gray-700 hover:text-blue-600 focus:outline-none"
              aria-label="切换菜单"
            >
              <i className="fa-solid fa-bars text-xl"></i>
            </button>
          </div>
        </div>

        {/* Mobile Navigation */}
        {isMenuOpen && (
          <div className="md:hidden mt-4 pb-4">
            <nav className="flex flex-col space-y-4">
              {navItems.map((item) => (
                item.anchor ? (
                  <button
                    key={item.anchor}
                    type="button"
                    onClick={() => handleAnchorClick(item.anchor!)}
                    className="text-gray-700 hover:text-blue-600 font-medium transition-colors text-left"
                  >
                    {item.label}
                  </button>
                ) : (
                  <Link
                    key={item.path}
                    to={item.path!}
                    className="text-gray-700 hover:text-blue-600 font-medium transition-colors"
                    onClick={() => setIsMenuOpen(false)}
                  >
                    {item.label}
                  </Link>
                )
              ))}
            </nav>
          </div>
        )}
      </div>
    </header>
  );
}